//
//  HelpTool.m
//  BeautyVideos
//
//  Created by shuihulu02 on 15/12/2.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "HelpTool.h"
// 百度统计
// 自定义指示器
#import "NSString+Ext.h"
#import "SFHFKeychainUtils.h"
#import "NSString+Ext.h"

@implementation HelpTool


+ (NSString *)getIOSuuid {
    
    NSString *strUUID =  [SFHFKeychainUtils getPasswordForUsername:@"uuid" andServiceName:@"com.weise.buiness" error:nil];
    if (strUUID.length == 0 || !strUUID) {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        [SFHFKeychainUtils storeUsername:@"uuid" andPassword:strUUID forServiceName:@"com.weise.buiness" updateExisting:YES error:nil];
    }
    //    [SFHFKeychainUtils deleteItemForUsername:@"uuid" andServiceName:@"com.baimihua.buiness" error:nil];
    return strUUID;
}


#pragma mark - 获取本地文件的大小
+ (unsigned long long)fileSizeForPath:(NSString *)path {
    signed long long fileSize = 0;
    NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
        if (!error && fileDict) {
            fileSize = [fileDict fileSize];
        }
    }
    return fileSize;
}

#pragma mark - 截取url字符串一部分，并使用utf8解码
+ (NSString *)getTextFromUrlString:(NSString *)urlString
{
    NSString *retStr = urlString;
    retStr = [retStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    retStr = [retStr stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    retStr = [retStr stringByReplacingOccurrencesOfString:@"	" withString:@""];
    
    // 去掉字符串中除json外多余字符
    NSInteger begin = [retStr rangeOfString:@"(" options:NSLiteralSearch].location+1;
    NSInteger end = [retStr rangeOfString:@")" options:NSBackwardsSearch].location;
    retStr = [retStr substringWithRange:NSMakeRange(begin, end - begin)];
    
    return retStr;
}

#pragma mark - 得到具体分享目标
+ (NSString *)shareGoalWithShareType:(ShareType1)type
{
    NSString *retStr = @"新浪微博";
    switch (type) {
        case ShareTypeQQPenple:{
            retStr = @"腾讯QQ";
            break;
        }
        case ShareTypeQQAllSpace:{
            retStr = @"QQ空间";
            break;
        }
        case ShareTypeWeixiPeople:{
            retStr = @"微信好友";
            break;
        }
        case ShareTypeWeixiAllLine:{
            retStr = @"微信好友圈";
            break;
        }
        default:
            break;
    }
    return retStr;
}

#pragma mark - 计算两个时间的天数差
+ (NSInteger)dateIntervelFrome:(NSDate *)from to:(NSDate *)to
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags fromDate:from toDate:to options:0];
    
    return [components day];
}

#pragma mark - 计算两个时间的分钟差
+ (NSInteger)minuteIntervelFrom:(NSDate *)from to:(NSDate *)to
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSMinuteCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags fromDate:from toDate:to options:0];
    
    return [components minute];
}

#pragma mark - 获取时间戳有多少秒
+ (NSInteger)secondTimeWithData:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    
    return [components second];
}

#pragma mark - 删除一个本地文件
+ (void)deleteLocalFileWithFilePath:(NSString *)filePath success:(DeleteLocalFileSuccessBlock)success failure:(DeleteLocalFileFailureBlock)failure
{
    // 如果文件存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
    }
    success();
}

#pragma mark - 百度统计
#pragma mark 页面统计

//记录某个页面访问的开始
+ (void)statPageStartWithPagename:(NSString *)pagename
{
  //  [[BaiduMobStat defaultStat] pageviewStartWithName:pagename];
}

//记录某个页面访问的结束
+ (void)statPageEndWithPagename:(NSString *)pagename
{
//    [[BaiduMobStat defaultStat] pageviewEndWithName:pagename];
}

#pragma mark 自定义事件统计

//记录一次事件的点击
+ (void)statEventId:(NSString*)eventId eventLabel:(NSString*)eventLabel
{
//    [[BaiduMobStat defaultStat] logEvent:eventId eventLabel:eventLabel];
}

//记录一次事件的开始
+ (void)statStartEventId:(NSString*)eventId eventLabel:(NSString*)eventLabel
{
//    [[BaiduMobStat defaultStat] eventStart:eventId eventLabel:eventLabel];
    
}

//记录一次事件的结束
+ (void)statEndEventId:(NSString *)eventId eventLabel:(NSString *)eventLabel
{
//    [[BaiduMobStat defaultStat] eventEnd:eventId eventLabel:eventLabel];
}


#pragma mark - 添加一个自动移除的提示
+ (void)startTipViewWithText:(NSString *)text duration:(CGFloat)duration type:(kTipViewType)type
{
    UIWindow *window = kDeviceWindow;
    
    // 背景
    UIView *bg = [[UIView alloc] init];
    [window addSubview:bg];
    bg.backgroundColor = RGBA(0, 0, 0, 0.8);
    bg.center = CGPointMake(kDeviceWindow.frame.size.width*0.5, kDeviceWindow.frame.size.height*0.5);
    bg.bounds = CGRectMake(0, 0, kDeviceWindow.frame.size.width-60, 60);
    bg.layer.masksToBounds = YES;
    bg.layer.cornerRadius = 6.0;
    bg.alpha = 1.0f;
    
    // 提示文字
    UILabel *label = [[UILabel alloc] init];
    [bg addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    
    label.font = kHelpToolTipLabelFont;
    label.text = text;
    CGSize labelSize = [text sizeWithFont:kHelpToolTipLabelFont maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    
    if (type == kTipViewTypeNone) {
        
        label.textAlignment = NSTextAlignmentCenter;
        label.frame = bg.bounds;
        
    }else if (type == kTipViewTypeCheckmark){
        // 勾
        UIImageView *checkmark = [[UIImageView alloc] init];
        [bg addSubview:checkmark];
        checkmark.image = [UIImage imageNamed:@"Checkmark"];
        checkmark.frame = (CGRect){{20,(60-checkmark.image.size.height)/2},checkmark.image.size};
        
        // 提示文字
        label.textAlignment = NSTextAlignmentCenter;
        CGFloat labelX = CGRectGetMaxX(checkmark.frame)+10;
        label.frame = (CGRect){{labelX, 0}, labelSize.width, bg.bounds.size.height};
        
    }
    
    [UIView animateWithDuration:0.5f delay:duration options:UIViewAnimationOptionCurveEaseOut animations:^{
        bg.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [bg removeFromSuperview];
    }];
}

#pragma mark - 设置文件不备份处理
+ (NSInteger)addSkipBackupAttributeToItemAtURL:(NSString *)path
{
    NSInteger ret = 1;
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        ret = -2;
        return ret;
    }
    NSError *error = nil;
    NSURL *URL = [NSURL fileURLWithPath:path];
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    if(!success){
        ret = -1;
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return ret;
}

#pragma mark - 获取view所在的控制器
+ (UIViewController *)viewControllerOfView:(UIView *)view
{
    for (UIView* next = [view superview]; next; next = next.superview)
    {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
    
}

//URLEncode
+(NSString*)encodeString:(NSString*)unencodedString{
    
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

//URLDEcode
-(NSString *)decodeString:(NSString*)encodedString

{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

/*
+ (NSString *)getImageCacheSize
{
    float tmpSize = [[SDImageCache sharedImageCache] getSize];
    NSString *cacheName = tmpSize >= 1? [NSString stringWithFormat:@"%.2fM",tmpSize] : [NSString stringWithFormat:@"%.2fK", tmpSize * 1024];
    return cacheName;
}

*/
+ (NSDictionary *)initWithGroupId:(NSString *)groupId senderId:(NSString *)senderId senderName:(NSString *)senderName senderFaceUrl:(NSString *)senderFaceUrl gradeIconUrl:(NSString *)gradeIconUrl messageText:(NSString *)messageText giftImageUrl:(NSString *)giftImageUrl WithGiftCount:(NSInteger)giftCount withGiftName:(NSString *)giftStr withAction:(int)action withGIFImage:(NSString *)GIFImageStr withFlowerGiftID:(NSString *)giftID{
    NSMutableDictionary *post = [NSMutableDictionary dictionary];
    [post setObject:groupId forKey:@"groupId"];
    
    if (senderId && senderId.length > 0)
    {
        [post setObject:senderId forKey:@"senderId"];
    }
    if (senderName && senderName.length > 0)
    {
        [post setObject:senderName forKey:@"senderName"];
    }
    if (senderFaceUrl && senderFaceUrl.length > 0)
    {
        [post setObject:senderFaceUrl forKey:@"senderFaceUrl"];
    }
    if (senderFaceUrl && senderFaceUrl.length > 0)
    {
        [post setObject:senderFaceUrl forKey:@"senderFaceUrl"];
    }
    if (gradeIconUrl && gradeIconUrl.length > 0)
    {
        [post setObject:gradeIconUrl forKey:@"gradeIconUrl"];
    }
    if (messageText && messageText.length > 0)
    {
        [post setObject:messageText forKey:@"messageText"];
    }
    if (giftImageUrl && giftImageUrl.length > 0)
    {
        [post setObject:giftImageUrl forKey:@"giftImageUrl"];
    }
    if (giftStr && giftStr.length > 0)
    {
        [post setObject:giftStr forKey:@"giftName"];
    }
    if (GIFImageStr && GIFImageStr.length > 0)
    {
        [post setObject:GIFImageStr forKey:@"giftMoveImageUrl"];
    }

    if (action > 0)
    {
        [post setObject:@(action) forKey:@"action"];
    }

    if (giftCount > 0)
    {
        [post setObject:@(giftCount) forKey:@"giftCount"];
    }
    if (giftID && giftID.length > 0)
    {
        [post setObject:giftID forKey:@"giftId"];
    }

    return post;
}


@end
